// import { encryptAES,decryptAES,generateAESKey } from '../utils/aes.js';
// export async function getDataByType(type) {
//   const response = await fetch(`http://localhost:3000/api/data/type?type=${type}`);
//   if (!response.ok) throw new Error('数据获取失败');
//   let rawData = await response.json();
//   const aesKey = generateAESKey();
//   const datas = encryptAES(rawData,aesKey,'1234567891234567');
//   rawData = decryptAES(datas,aesKey,'1234567891234567');
//   return rawData.map(item => ({
//     ...item,
//     percentage: parseFloat(item.percentage) || 0
//   }));
// }//未加密的get方法

import { secureFetch } from './secureRequest';
export async function getDataByType(type) {
  const response = await secureFetch('/data/type', type);
  // if (!response.ok) throw new Error('数据获取失败');
  // const rawData = await response.json();
  const rawData = response;
  return rawData.map(item => ({
    ...item,
    percentage: parseFloat(item.percentage) || 0
  }));
}//加密的post方法

export async function getResult(destination, weight){
	const response = await secureFetch('/data/calculate', [destination, weight]);
	// if (!response.ok) throw new Error('数据获取失败');
	// const rawData = await response.json();
	return response;
}
//RegionList.vue
export function getProvinces(data) {
  return data
    .filter(item => item.v_par_code == '0')
    .map(item => ({
      code: item.v_dist_code,
      name: item.v_dist_name,
      percentage: item.percentage
    }))
    .sort((a, b) => b.percentage - a.percentage);
}

export function getCitiesByProvince(data, provinceCode) {
  return data
    .filter(item => item.v_par_code == provinceCode)
    .map(item => ({
      code: item.v_dist_code,
      name: item.v_dist_name,
      percentage: item.percentage
    }))
    .sort((a, b) => b.percentage - a.percentage);
}

export function searchRegion(data, query) {
  const pro_results = [];
  const city_results = [];
  if (!query) return [];

  // 遍历所有省份
  data.forEach( item => {
    // 检查省份名称是否匹配
    if (item.v_dist_name.includes(query)) {
      if (item.v_par_code == '0') {
        pro_results.push(
          {
            par_code: item.v_dist_code,
            code: item.v_dist_code,
            name: item.v_dist_name,
            percentage: item.percentage
          } 
         ); // 添加省份信息
      }
      else if (item.v_par_code !== '0') {
        let parentCode = item.v_par_code;
        let par_persentage = data.filter(item => item.v_dist_code == parentCode)[0].percentage;
        city_results.push(
          {
            par_code: item.v_par_code,
            code: item.v_dist_code,
            name: item.v_dist_name,
            percentage: par_persentage
          }
         ); // 添加城市信息
      }
    } 
  });
  pro_results.sort((a, b) => b.percentage - a.percentage);//对省份结果排序
  city_results.sort((a, b) => b.percentage - a.percentage);//对城市结果排序
  let results =  pro_results.concat(city_results);//合并省份和城市结果

  return results;
}